package gen.tools.delivery;

import gen.tools.Widgets;
import gen.tools.structures.Personnel;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class QueryMailList extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public QueryMailList() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String strSQL = "SELECT empId, empName, empEmail, empPhone FROM emps";
		final ArrayList<Personnel> personnels = new ArrayList<Personnel>();

		try {
			conn = wid.getConn();
			ps = conn.prepareStatement(strSQL);
			rs = ps.executeQuery();
			while (rs.next()) {
				final Personnel p = new Personnel();
				p.setId(rs.getString("empId"));
				p.setName( rs.getString("empName") );
				p.setEmail(rs.getString("empEmail"));
				p.setPhone(rs.getString("empPhone"));
				personnels.add(p);
			}
		} catch ( Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (ps != null) {ps.close();}
				if (conn != null) {conn.close();}	
			} catch (SQLException e ) {
				System.out.println(wid.errProcess(e));
			}
		}

		response.getWriter().write(new Gson().toJson(personnels));
	
		
	}

}
